const express = require('express'); // 框架
const url = require('url'); // url模块
const moment = require('moment');

const response = require('module/response'); // 响应
const validate = require('module/validate'); // 验证
const Page = require('entity/page'); // 分页

const commentService = require('service/comment-service');

const router = express.Router(); // 路由

/**
 * 获取分页数据
 */
router.get('/getPageList/:manage?', (req, res, next) => {
  let sourceManage = req.params.manage === '1'; // 来源是否是管理系统
  let paramsT = url.parse(req.url, true).query; // url参数获取
  // 参数转换
  let params = {
    flash_id: paramsT.flash_id, // flash id
    pageNum: Number(paramsT.pageNum),
    pageSize: Number(paramsT.pageSize),
    audit_state: paramsT.audit_state ? Number(paramsT.audit_state) : '' // 审核状态
  }
  // 如果非后台管理系统-设置参数
  if (!sourceManage) {
    params.audit_state = 2; // 审核状态
  }
  // 参数验证
  let msgs = validate(params, {
    flash_id: {required: sourceManage ? false : true},
    pageNum: {str: '页码', type: 'number'},
    pageSize: {str: '每页条数', type: 'number'},
    audit_state: {str: '审核状态', type: 'number'}
  });
  if (msgs) {
    response(res, null, null, 8001, msgs);
    return false;
  }
  commentService.getPageList(params, (err, result) => {
    for (let item of result) {
      item.time = moment(item.time).format('YYYY-MM-DD HH:mm:ss');
    }
    let page = new Page(params.pageNum, params.pageSize, result ? result.total : 0, result);
    response(res, page, err);
  });
});

/**
 * 新增
 */
router.post('/add', (req, res, next) => {
  let paramsT = req.body; // 参数获取
  // 参数转换
  let params = {
    flash_id: paramsT.flash_id, // flash id
    content: paramsT.content, // 评论内容
    user_name: paramsT.user_name // 评论人
  }
  // 参数验证
  let msgs = validate(params, {
    flash_id: {str: '文件ID', required: true},
    content: {str: '评论内容', required: true},
    user_name: {str: '评论人', required: true}
  });
  if (msgs) {
    response(res, null, null, 8001, msgs);
    return false;
  }
  commentService.add(params, (err, result) => {
    response(res, null, err);
  });
});

/**
 * 删除
 */
router.post('/remove', (req, res, next) => {
  let paramsT = req.body; // 参数获取
  // 参数转换
  let params = {
    ids: paramsT.ids // id列表
  }
  // 参数验证
  let msgs = validate(params, {
    ids: {required: true}
  });
  if (msgs) {
    response(res, null, null, 8001, msgs);
    return false;
  }
  commentService.remove(params.ids, (err, result) => {
    response(res, null, err);
  });
});

/**
 * 审核 2通过 3驳回
 */
router.post('/audit', (req, res, next) => {
  let paramsT = req.body; // 参数获取
  // 参数转换
  let params = {
    ids: paramsT.ids, // id列表
    audit_state: paramsT.audit_state // 审核状态
  }
  // 参数验证
  let msgs = validate(params, {
    ids: {required: true},
    audit_state: {required: true, type: 'number'}
  });
  commentService.audit(params, (err, result) => {
    response(res, null, err);
  });
});

module.exports = router;
